//https://leetcode.cn/problems/4sum/description/

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        sort(nums.begin(), nums.end());
        int n = nums.size();

        vector<vector<int>> ret;

        for (int i = 0; i < n - 3;) {

            for (int j = i + 1; j < n - 2;) {
                int r2 = j + 1;
                int r1 = n - 1;
                while (r2 < r1) {

                    long long temp = nums[r2] + nums[r1];
                    long long A = (long long)target - nums[i] - nums[j];
                    if (temp < A) {
                        r2++;
                        continue;
                    }
                    else if (temp > A) {
                        r1--;
                        continue;
                    }
                    else {
                        ret.push_back({ nums[i], nums[j], nums[r2], nums[r1] });
                        while (r2 < r1 && nums[r2 + 1] == nums[r2])
                            r2++;
                        while (r2 < r1 && nums[r1 - 1] == nums[r1])
                            r1--;
                        r2++;
                        r1--;

                        continue;
                    }
                }
                j++;
                while (j < n && nums[j] == nums[j - 1])
                    j++;
            }
            i++;
            while (i < n && nums[i] == nums[i - 1])
                i++;
        }
        return ret;
    }
};
